package com.shiwaixiangcun.customer.presenter.impl;

import android.content.Context;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.shiwaixiangcun.customer.GlobalApi;
import com.shiwaixiangcun.customer.GlobalConfig;
import com.shiwaixiangcun.customer.entity.ImageReturnBean;
import com.shiwaixiangcun.customer.entity.ResponseEntity;
import com.shiwaixiangcun.customer.network.HttpCallBack;
import com.shiwaixiangcun.customer.network.HttpRequest;
import com.shiwaixiangcun.customer.presenter.IOnlineServicePresenter;
import com.shiwaixiangcun.customer.ui.IOnlineServiceView;
import com.shiwaixiangcun.customer.ui.dialog.DialogLoading;
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr;
import com.shiwaixiangcun.customer.utils.JsonUtil;
import com.shiwaixiangcun.customer.utils.LoginOutUtil;
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author Administrator
 * @date 2017/5/25
 */

public class OnlineServiceImpl implements IOnlineServicePresenter {
    String refreshToken;
    private String strToken;
    private IOnlineServiceView iOnlineServiceView;
    private String content;
    private HashMap<String, File> hashImage;
    private String strImaid = "";
    private String sImageid = "";
    private DialogLoading mDialogLoading;
    private List<File> list_file = new ArrayList<>();
    private Long typeID;


    public OnlineServiceImpl(Context context, Long id, IOnlineServiceView iOnlineServiceView, String content, HashMap<String, File> hashImage) {
        this.iOnlineServiceView = iOnlineServiceView;
        mDialogLoading = new DialogLoading(context, "正在提交");
        this.content = content;
        this.hashImage = hashImage;
        this.typeID = id;
    }

    public OnlineServiceImpl(Long id) {
        this.typeID = id;
    }


    @Override
    public void setBgaAdpaterAndClick(Context context) {
        sendDataWithoutImage(context);
    }

    @Override
    public void setHaveImageClick(Context context) {

        mDialogLoading.show();

        putImageToService(context);
    }

    @Override
    public void setInformation(Context context) {
//        sendInformationHttp(context);
    }

    /**
     * 提交数据（不带图片）
     *
     * @param context
     */
    private void sendDataWithoutImage(final Context context) {
        int siteID = (int) AppSharePreferenceMgr.get(context, GlobalConfig.CURRENT_SITE_ID, 20);
        refreshToken = (String) AppSharePreferenceMgr.get(context, GlobalConfig.Refresh_token, "");
        strToken = (String) AppSharePreferenceMgr.get(context, GlobalConfig.TOKEN, "");
        HashMap<String, Object> hashMap = new HashMap<>(4);
        hashMap.put("access_token", strToken);
        hashMap.put("content", content);
        hashMap.put("typeId", typeID);
        hashMap.put("siteId", siteID);
        HttpRequest.post(GlobalApi.INSTANCE.getOnlineRepair(), hashMap, new HttpCallBack() {
            @Override
            public void onSuccess(String responseJson) {

                mDialogLoading.close();
                Type type = new TypeToken<ResponseEntity>() {
                }.getType();
                ResponseEntity responseEntity = JsonUtil.fromJson(responseJson, ResponseEntity.class);
                if (responseEntity == null) {
                    return;
                }
                switch (responseEntity.getResponseCode()) {
                    case 1001:
                        iOnlineServiceView.setBgaAdpaterAndClickResult(responseEntity);
                        break;
                    case 1002:
                        Toast.makeText(context, responseEntity.getMessage(), Toast.LENGTH_SHORT).show();
                        break;
                    case 1018:
                        RefreshTokenUtil.refreshToken(context, refreshToken);
                        break;
                    case 1019:
                        LoginOutUtil.sendLoginOutUtil(context);
                        break;
                    default:
                        break;


                }


            }

            @Override
            public void onFailed(Exception e) {
                mDialogLoading.close();
            }
        });
    }

    /**
     * 提交图片到服务器
     *
     * @param context
     */
    private void putImageToService(final Context context) {
        for (int i = 0; i < list_file.size(); i++) {
            list_file.remove(i);
        }

        Iterator iter = hashImage.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            Object val = hashImage.get(key);
            list_file.add((File) val);
        }


        refreshToken = (String) AppSharePreferenceMgr.get(context, GlobalConfig.Refresh_token, "");
        strToken = (String) AppSharePreferenceMgr.get(context, GlobalConfig.TOKEN, "");
        HashMap<String, Object> hashMap = new HashMap<>(2);
        hashMap.put("access_token", strToken);
        hashMap.put("images", list_file);


        HttpRequest.post(GlobalApi.INSTANCE.getFileSend(), hashMap, new HttpCallBack() {
            @Override
            public void onSuccess(String responseJson) {
                mDialogLoading.close();
                Type type = new TypeToken<ResponseEntity<List<ImageReturnBean>>>() {
                }.getType();
                ResponseEntity<List<ImageReturnBean>> responseEntity = JsonUtil.fromJson(responseJson, type);
                iOnlineServiceView.setHaveImageResult(responseEntity);

                if (responseEntity.getResponseCode() == 1001) {
                    List<ImageReturnBean> data_image = responseEntity.getData();
                    for (int i = 0; i < data_image.size(); i++) {
                        strImaid += data_image.get(i).getFileId() + ",";
                    }
                    sImageid = strImaid.substring(0, strImaid.length() - 1);

                    putDataWithImage(context, sImageid);
                }
            }

            @Override
            public void onFailed(Exception e) {
                mDialogLoading.close();
            }
        });
    }

    /**
     * 提交数据到服务器  （存在图片的情况）
     *
     * @param context
     * @param s_imageId
     */
    private void putDataWithImage(Context context, String s_imageId) {

        int siteID = (int) AppSharePreferenceMgr.get(context, GlobalConfig.CURRENT_SITE_ID, 20);
        refreshToken = (String) AppSharePreferenceMgr.get(context, GlobalConfig.Refresh_token, "");
        strToken = (String) AppSharePreferenceMgr.get(context, GlobalConfig.TOKEN, "");
        HashMap<String, Object> hashMap = new HashMap<>(8);
        hashMap.put("access_token", strToken);
        hashMap.put("content", content);
        hashMap.put("imageIds", s_imageId);
        hashMap.put("typeId", typeID);
        hashMap.put("siteId", siteID);
        HttpRequest.post(GlobalApi.INSTANCE.getOnlineRepair(), hashMap, new HttpCallBack() {
            @Override
            public void onSuccess(String responseJson) {
                mDialogLoading.close();
                Type type = new TypeToken<ResponseEntity>() {
                }.getType();
                ResponseEntity responseEntity = JsonUtil.fromJson(responseJson, ResponseEntity.class);
                iOnlineServiceView.setHaveImageResult(responseEntity);


            }

            @Override
            public void onFailed(Exception e) {
                mDialogLoading.close();
            }
        });
    }



}
